package cat.joronya.supermanager.home;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;

public class HomeActivity extends Activity 
{
	private final String TAG = "supermanager";
	private Cursor cursor = null;
	private HomeObserver homeObserver = null;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        
        cursor = getContentResolver().query(Supermanager.Home.CONTENT_URI, 
        		Supermanager.Home.PROJECTION, 
           		null,
           		null,
                Supermanager.Home.DEFAULT_SORT_ORDER);
        
        homeObserver = new HomeObserver(new Handler());
        
        getContentResolver().registerContentObserver(Supermanager.Home.CONTENT_URI, 
        		false, homeObserver);
        
        updateHomeFields();
    }
    
    @Override
	protected void onDestroy() 
    {
    	getContentResolver().unregisterContentObserver(homeObserver);
		super.onDestroy();
	}

	/**
     * Update fields.
     */
    private void updateHomeFields()
    {
    	final TextView day = (TextView) findViewById(R.id.home_day);
    	final LinearLayout duetimeRow = (LinearLayout) findViewById(R.id.home_duetime_row);
		final TextView duetime = (TextView) findViewById(R.id.home_duetime);
		final WebView homeInfo = (WebView) findViewById(R.id.home_info);
		final ImageView status = (ImageView) findViewById(R.id.home_status);

		if( cursor.moveToFirst() )
        {   
			/*String html = "<p align=\"justify\">¡Ya tenemos ganadores entre los "+
				"<b><font color=red>368.163 equipos</font></b> que han participado "+
				"en el SuperManager 2010-11!<br><br>ole tu ole tu</p>";*/
    		day.setText(getString(R.string.home_day, cursor.getString(1)));
    		String duetimeValue = cursor.getString(4);
    		if( duetimeValue != null )
    		{
    			duetime.setText(getString(R.string.home_duetime, duetimeValue));
    			duetimeRow.setVisibility(View.VISIBLE);
    		}
    		else
    		{
    			duetimeRow.setVisibility(View.GONE);
    		}
    		homeInfo.loadDataWithBaseURL("http://supermanager.acb.com", cursor.getString(3), "text/html","utf-8", "");
    		switch(new Integer(cursor.getString(2)))
    		{
    			case Supermanager.CLOSED_STATUS:
    				status.setImageResource(R.drawable.closed);
    				break;
    			case Supermanager.OPEN_NO_CHANGES_STATUS:
    				status.setImageResource(R.drawable.open_changes_closed);
    				break;
    			case Supermanager.OPEN_STATUS:
    				status.setImageResource(R.drawable.open);
    				break;
    			case Supermanager.AUTH_ERROR_STATUS:
    			case Supermanager.OTHER_ERROR_STATUS:
    			case Supermanager.CONNECTIVITY_ERROR_STATUS:
    				status.setImageResource(R.drawable.error);
    				break;
    			default:
    				status.setImageResource(R.drawable.refresh);
    		}
        }
		else
		{
    		day.setText(getString(R.string.home_day, ""));
    		duetime.setText(getString(R.string.home_duetime, ""));
    		homeInfo.loadData(getString(R.string.home_info, ""),"text/html","ISO-8859-1");
    		status.setImageResource(R.drawable.refresh);		
		}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.market, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.refresh:
        		// mirem si tenim user/password a les preferences
           		SharedPreferences settings = 
           			getSharedPreferences(Supermanager.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
           		final String username = settings.getString("username", null);
           		final String password = settings.getString("password", null);
           		
				// cridar refresh al REST method
				SupermanagerServiceHelper.getInstance(this).login(username,password,handler);
				return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    private Handler handler = new Handler() 
    { 
        @Override 
        public void handleMessage(Message msg)
        { 
            //get data from msg 
            int status = msg.getData().getInt("status"); 
            Log.d(TAG, "HomeActivity received status: "+status);
            
            Toast.makeText(getApplicationContext(), 
            		"Home info updated!", 
            		Toast.LENGTH_SHORT).show();
            
            super.handleMessage(msg); 
        } 
    };

    /**
     * Observer to register Home content and keep updated
     * HomeActivity content.
     * @author pol
     *
     */
    class HomeObserver extends ContentObserver
    {
		public HomeObserver(Handler handler) 
		{
			super(handler);
		}
    	
		@Override
		public boolean deliverSelfNotifications() 
		{
			return false;
		}

		@Override
		public void onChange(boolean selfChange) 
		{
			super.onChange(selfChange);
			updateHomeFields();
		}
    }
    
}
